package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;


import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.CmdTypeEnum;
import com.wtwd.device.constant.DeviceLoginEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.mq.PushMsgService;
import com.wtwd.wtwddevice.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录协议处理
 * 1.设备上线,更新设备信息
 * 2.回复设备
 */

@MsgType(MsgTypeEnum.DEVICE_LOGIN)
@Component
public class LoginHandlerImpl implements IMsgHandler {

   @Autowired
    private IDeviceService deviceService;

    @Resource
    private PushMsgService msgService;

    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol protocol = messageBase.getWtProtocol();
        DeviceLoginEnum deviceLoginEnum = DeviceLoginEnum.DEVICE_FAIL;
        if (deviceService.deviceLogin(messageBase.getForm(), protocol)) {
            deviceLoginEnum = DeviceLoginEnum.DEVICE_SUCCESS;
        }
        protocol.setTime(DateUtils.format(new Date(), DateUtils.dateFormat15));
        protocol.setBodyLength(deviceLoginEnum.getBody().length());
        protocol.setBody(deviceLoginEnum.getBody());
        protocol.setMesType(CmdTypeEnum.REPORT_RESPONSE.getCmdType().toString());
        msgService.pushToDevice(messageBase.getForm(),
                MessageBase.builder().deviceKey(protocol.getImei())
                        .wtProtocol(protocol)
                        .build());
    }

}
